<template>
  <!-- 冷铁需求详情表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="60%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="80"
    >
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            max-height="710"
            :data="formData.data"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="冷铁名称"
              prop="ironName"
              min-width="200"
              show-overflow-tooltip
            />
            <el-table-column
              label="日期"
              prop="ironDate"
              min-width="100"
              show-overflow-tooltip
              :formatter="formatDate"
              align="center"
            />
            <el-table-column
              label="下线数量"
              prop="quantity"
              min-width="200"
              show-overflow-tooltip
              align="right"
            />
            <el-table-column
              label="是否新生产"
              align="center"
              prop="issquantity"
              min-width="100"
            >
              <template #default="scope">
                <el-switch
                  v-model="scope.row.issquantity"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                  @change="handleAdStatusChange(scope.row, scope.$index)"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="生产数量"
              props="squantity"
              min-width="200"
              header-align="center"
              align="right"
            >
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
                <el-form-item
                  :prop="'data.' + $index + '.squantity'"
                  :rules="rules.squantity"
                  label-width="0px"
                  class="center-input"
                >
                  <el-input
                    v-model="row.squantity"
                    v-if="row.issquantity > 0"
                    placeholder="请输入"
                  />
                  <span v-else>{{ row.squantity }}</span>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESIRONDEMANDDETAILADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  organizationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  organizationCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  plantCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  ironId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  ironName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  quantity: [],
  oId: [{ min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" }],
  ironDate: [],
  squantity: [
    { required: true, message: "请输入数量", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  status: [],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  deleted: [],
});

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
const formRef = ref(ElForm);

let formData = reactive({
  data: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    const { data } = newVal;
    Object.assign(formData, {
      data,
    });
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.data = [];
}

const loading = ref(false);

/** 冷铁需求详情保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "操作";
      await request({
        url: "/mes/mesirondemanddetail/saveBatchRelease",
        method: "post",
        data: formData.data,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}

function handleAdStatusChange(row, idx) {
  if (row.issquantity === 1) {
    row.squantity = 1;
  } else {
    row.squantity = 0;
  }
}
</script>
